package com.cuit.blog.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.AntPathMatcher;

import com.cuit.blog.entity.User;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

// @WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
// @WebFilter注解用于声明当前类是一个过滤器类，对应的参数为过滤器名称和过滤路径，/*意味着全局过滤。
// 当添加@Component注解时，会对全局进行过滤
public class LoginFilter implements Filter {
    // 路径匹配器,AntPathMatcher是spring的一个用于路径匹配的工具类
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
	    throws IOException, ServletException {
	// 获取Http请求和响应对象
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	HttpServletResponse response = (HttpServletResponse) servletResponse;
	// 获取当前请求路径信息
	String requestURI = request.getRequestURI();
	System.out.println("获取请求信息：" + requestURI);
	// 过滤路径，设置不过滤的请求
	String[] urls = { "/login",
			"/Test/**",
		"/user/login",
		"/normaluser/**",
		"/logout", 
		"/css/**", 
		"/js/**", 
		"/image/**" };
	boolean check = check(requestURI, urls);
	// 白名单请求则放行
	if (check) {
	    filterChain.doFilter(request, response);
	    return;
	}
	// 验证登录状态,已登录则放行
	if (request.getSession().getAttribute("LoginUser") != null) {
	    User loginUser = (User) request.getSession().getAttribute("LoginUser");
	    System.out.println("login user:" + loginUser.getUsername());
	    filterChain.doFilter(request, response);
	    return;
	}
	// 否则就是未登录状态，根据前端js，应该以输出流的方式向客户端响应数据
	// 这里是前端对返回值进行了一个判断，如果值是对应返回值则跳转到登录页面
	response.sendRedirect("/login");
//	response.setContentType("text/html; charset=utf-8");
//	response.getWriter().write("你还没有登陆！！！");
//	response.getWriter().write("<a href='/login'>登录页面</a>");
	return;
    }

    public boolean check(String requestURI, String[] urls) {
	for (int i = 0; i < urls.length; i++) {
	    // match方法用于匹配路径，确定路径是否一致，相同返回true，不同返回false
	    boolean match = PATH_MATCHER.match(urls[i], requestURI);
	    if (match) {
		return true;
	    }
	}
	return false;
    }
}
